# coding=utf-8

import time
from ftplib import FTP
import os

remote_path = "data/"  # 远端目录

begin_time = 830  # 任务开始时间
end_time = 1800  # 任务结束时间

today = time.strftime("%Y%m%d")  # 当天日期
local_path = './data/'
if not os.path.exists(local_path):
    os.mkdir(local_path)
log_path = './log/'
if not os.path.exists(log_path):
    os.mkdir(log_path)
log_file = log_path + 'ftp_log.txt'
local_file_list = os.listdir(local_path)


def ftp_connect(ftpserver, port, username, password):
    """用于FTP连接"""
    ftp = FTP()
    try:
        ftp.connect(ftpserver, port)
        ftp.login(username, password)
    except:
        raise IOError('\n FTP connection failed, please check the code!')
    else:
        print(ftp.getwelcome())  # 打印登陆成功后的欢迎信息
        print('\n+------- ftp connection successful!!! --------+')
        return ftp


def ftpDownloadFile(ftp, ftpfile, local_file):
    bufsize = 1024
    with open(local_file, 'wb') as fid:
        ftp.retrbinary('RETR {0}'.format(ftpfile), fid.write, bufsize)  # 接收服务器文件并写入本地文件


def ftpDownload(ftp, remote_path, local_path):
    """用于目标文件下载"""
    ftp.cwd(remote_path)
    print('------download---------')

    for file in ftp.nlst():
        local = os.path.join(local_path, file)
        if os.path.isdir(file):
            if not os.path.exists(local):  # 判断是否为子目录
                os.makedirs(local)
            ftpDownload(ftp, file, local)  # 递归调用
        else:
            if file not in local_file_list:
                print(file)
                ftpDownloadFile(ftp, file, local)
    ftp.cwd('..')
    ftp.quit()
    return True


if __name__ == '__main__':
    ftp_server = "192.168.30.36"  # ftp站点对应的IP地址
    username = 'data'
    password = 'data'
    ftp = ftp_connect(ftp_server, 21, username, password)

    while True:
        if int(time.strftime("%H%M")) in range(begin_time, end_time):  # 判断是否在执行时间范围
            if int(time.strftime('%Y%m%d')) - int(today) == 0:  # 判断是否跨日期
                flag = ftpDownload(ftp, remote_path, local_path)
                with open(log_file, 'a') as f:
                    f.write('\n' + time.strftime("%Y/%m/%d %H:%M:%S") + " 今日文件已下载！")
                    time.sleep(60)  # 下载完毕静默1分钟
                break
            else:
                break
                """如果跨日期, 则根据当前日期，更新各文件日期"""
                # today = time.strftime("%Y%m%d")  # 当天日期
                # today_file = today + '.jpg'  # 得到当天日期的目标文件名
                # remote_file = remote_path + today_file  # 远端文件名
                # local_file = '\\local\\' + today + '\\' + today_file  # 本地文件名

                # with open(log_file, 'a') as f:
                #     f.write('\n' + time.strftime("%Y%m%d %H:%M:%S") + "任务启动， 文件日期已更新.")
        else:
            time.sleep(1800)
